package com.health.mapp.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import redis.clients.jedis.Jedis;

import com.health.mapp.service.Adapter;
import com.health.mapp.service.Service;
import com.health.commons.CommonsUtils;
import com.health.commons.PropertiesService;
import com.health.commons.Reflection;
import com.health.db.cache.DBCacheFactory;
import com.health.mapp.utils.MappGlobal;
import com.health.redis.RedisClient;
 
public class Service extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5362613219871271796L;

	private static Logger logger = Logger.getLogger(Service.class);

	/**
	 * Constructor of the object.
	 */
	public Service() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		String remoteIP=SecureUtil.getRemoteHost(request);
		logger.debug("remoteIP:"+remoteIP);
		try
		{
			
			//RedisClient.visiterIPLimit(remoteIP, 50);
			  
		}
		catch(Exception e)
		{
			
			logger.error("remoteIP:"+e.getCause());
		}
		int bodyLen = request.getContentLength();
	
		byte[] buffer = new byte[bodyLen];

		int post = 0;
		//缓冲读，每次读4096字节
		byte[] cache = new byte[4096];
//		ByteArrayInputStream originalContent = new ByteArrayInputStream(buffer);
//		ByteArrayInputStream bais= new ByteArrayInputStream(buffer);
//		GZIPInputStream gzipIn = new GZIPInputStream(bais);
//		 
//		originalContent.read(gzipIn);
//		gzipIn.close();
		while (post < bodyLen) {
			int len = request.getInputStream().read(cache);
			if (len <= 0) {
				logger.error("READ SOCKET ERROR!");
				break;
			}
			System.arraycopy(cache, 0, buffer, post, len);
			post += len;
		}

		//for(int i=0;i<buffer.length;i++)
		//{
			logger.debug("Request  [" + new String(buffer) + "]");
			//System.out.print((char)buffer[i]);
		//}
		
	//	System.out.println();
		Adapter adapter = new Adapter();
		adapter.setRequest(request);
		
		//调用适配器，其实bodyLen和buffer.size是一样大小的
		String result = adapter.execute(bodyLen, buffer);

		//logger.debug("execute:" + result);

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(result);
		out.println("\r\n");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		logger.debug("soft init...");
		String path = getServletContext().getRealPath(File.separator);
		PropertyConfigurator.configure(path + "/WEB-INF/classes/log4j.properties");
		logger.debug("WebRootPath:"+path);
		MappGlobal.getInstance().setWebRootPath(path);

		String configPath = getServletContext().getRealPath(File.separator);
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(configPath + "/WEB-INF/classes/resources/config.properties");
			prop.load(fis);
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		MappGlobal.getInstance().setSoftDetailUrl(prop.getProperty("soft.detail.url"));

		MappGlobal.getInstance().setDetailPrefixUrl(prop.getProperty("detailPrefixUrl"));

		logger.debug("soft.detail.url=" + MappGlobal.getInstance().getSoftDetailUrl());

		Enumeration<Object> keyEnumeration = prop.keys();

		while (keyEnumeration.hasMoreElements()) {
			Object key = keyEnumeration.nextElement();
		//	logger.debug("MappGlobal key:"+key.toString()+",MappGlobal value:"+ prop.get(key).toString());
			MappGlobal.getInstance().getPropertiesConfig().put(key.toString(), prop.get(key).toString());
		}

	}

}
